﻿using Base.FileRemoteModel.UserFile.Model;
using Basic.FormCollect;
using Basic.FormExtendService;
using Basic.FormModel.AgentForm;
using Basic.FormModel.QueryColumn;
using Basic.FormModel.QueryTable;
using Basic.FormRemoteModel;
using Basic.FormRemoteModel.QueryInter.Model;
using Basic.FormRemoteModel.TableRecord.Model;
using Basic.UserFormService.Interface;
using Basic.UserFormService.PhysicsTable.Model;
using WeDonekRpc.Helper;

namespace Basic.UserFormService.PhysicsTable
{
    internal class PhysicsAddRowService : IPhysicsAddRowService
    {
        private readonly IAgentFormCollect _AgentForm;
        private readonly IQueryColumnCollect _Column;
        private readonly IQueryTableCollect _Table;
        private readonly IFileService _File;
        public PhysicsAddRowService ( IAgentFormCollect agent,
            IQueryColumnCollect column,
            IFileService file,
            IQueryTableCollect table )
        {
            this._File = file;
            this._AgentForm = agent;
            this._Column = column;
            this._Table = table;
        }
        private Dictionary<long, FormVal> _Values;
        private long _LogId;
        private readonly List<FormFileVal> _Files = new List<FormFileVal>();
        public bool AddRow ( Dictionary<long, FormVal> vals, TableDataRow row )
        {
            QueryCol[] cols = this._Column.GetsByFormId<QueryCol>(row.ToFormId);
            if ( cols.IsNull() )
            {
                return false;
            }
            this._Values = row.Relation.ToDictionary(a => a.ToColId, a => vals.GetValueOrDefault(a.ColId));
            this._LogId = row.LogId;
            PhyQueryTable[] tables = this._Table.Gets(row.ToFormId);
            PhyQueryTable main = tables.Find(c => c.IsMainTable);
            TableAddData add = new TableAddData
            {
                TableName = main.TableName,
                LinkPk = row.LinkPK,
                LinkType = row.LinkType,
                CompanyId = row.CompanyId,
                Column = new Dictionary<string, object>(),
                Children = new List<SubTableRow>()
            };
            if ( !tables.TrueForAll(t =>
            {
                QueryCol[] list = cols.FindAll(c => c.TableId == t.Id && c.ShowMode == PhyColShowMode.Column);
                if ( t.IsMainTable )
                {
                    return this._FillMainTable(add, list);
                }
                else
                {
                    return this._FillRow(t, add, list);
                }
            }) )
            {
                return false;
            }
            long id = this._AgentForm.Add(add);
            if ( this._Files.Count > 0 )
            {
                this._File.CopyFile(this._Files.ConvertAllToArray(c => new UserFileCopy
                {
                    FileId = c.FileId,
                    DirKey = c.DirKey,
                    LinkPk = id,
                    Tag = c.Index.HasValue ? c.Index.Value.ToString() : null
                }));
            }
            return true;
        }
        private bool _FillRow ( PhyQueryTable table, TableAddData add, QueryCol[] cols )
        {
            if ( cols.IsNull() )
            {
                return true;
            }
            int rowNum = this._Values.Where(c => cols.IsExists(a => a.Id == c.Key) && !c.Value.IsNull).Select(c => c.Value.ListItem.Len).FirstOrDefault();
            if ( rowNum <= 0 )
            {
                return false;
            }
            for ( int i = 0 ; i < rowNum ; i++ )
            {
                SubTableRow row = new SubTableRow
                {
                    TableName = table.TableName,
                    Column = new Dictionary<string, object>()
                };
                if ( !cols.TrueForAll(c =>
                {
                    FormVal val = this._Values.GetValueOrDefault(c.Id);
                    if ( ( val == null || val.IsNull ) && c.IsNull == false && c.DefValue.IsNull() )
                    {
                        return false;
                    }
                    object value = null;
                    if ( ( val == null || val.IsNull ) && !c.DefValue.IsNull() )
                    {
                        value = c.CovertDefFormat();
                    }
                    else if ( val != null && val.IsNull == false )
                    {
                        if ( c.FuncType == FormColumnFuncType.上传的附件 )
                        {
                            this._Files.Add(new FormFileVal
                            {
                                FileId = val.Vals.ConvertAll(a => long.Parse(a)),
                                Index = i,
                                DirKey = Convert.ToString(c.ColumnSet["DirKey"])
                            });
                        }
                        value = val.ListItem.GetFormValue(i);
                    }
                    row.Column.Add(c.ColName, value);
                    return true;
                }) )
                {
                    return false;
                }
                add.Children.Add(row);
            }
            return true;
        }
        private bool _FillMainTable ( TableAddData add, QueryCol[] cols )
        {
            if ( cols.IsNull() )
            {
                return true;
            }
            return cols.TrueForAll(c =>
            {
                if ( c.FuncType == FormColumnFuncType.审批日志ID )
                {
                    add.Column.Add(c.ColName, this._LogId);
                    return true;
                }
                FormVal val = this._Values.GetValueOrDefault(c.Id);
                if ( ( val == null || val.IsNull ) && c.IsNull == false && c.DefValue.IsNull() )
                {
                    return false;
                }
                object value = null;
                if ( ( val == null || val.IsNull ) && !c.DefValue.IsNull() )
                {
                    value = c.CovertDefFormat();
                }
                else if ( val != null && !val.IsNull )
                {
                    if ( c.FuncType == FormColumnFuncType.上传的附件 )
                    {
                        this._Files.Add(new FormFileVal
                        {
                            FileId = val.Vals.ConvertAll(a => long.Parse(a)),
                            DirKey = Convert.ToString(c.ColumnSet["DirKey"])
                        });
                    }
                    value = val.GetFormValue();
                }
                add.Column.Add(c.ColName, value);
                return true;
            });
        }
    }
}
